// src/main/java/mr/ali/webvideo/controller/WeChatPayController.java
package mr.ali.webvideo.controller;

import lombok.extern.slf4j.Slf4j;
import mr.ali.webvideo.Exception.R;
import mr.ali.webvideo.model.WeChatPayRequest;
import mr.ali.webvideo.model.WeChatPayResponse;
import mr.ali.webvideo.service.impl.WeChatPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/h5/api/pay")
@Slf4j
public class WeChatPayController {

    @Autowired
    private WeChatPayService weChatPayService;

    @Value("${wechat.notifyUrl}")
    private String notifyUrl;

    /**
     * 创建微信支付订单
     * @param request 支付请求参数
     * @param httpRequest HTTP请求对象，用于获取客户端IP
     * @return 支付参数
     */
    @PostMapping("/wechat/jsapi")
    public R<WeChatPayResponse> createWeChatPayment(@RequestBody WeChatPayRequest request,
                                                   HttpServletRequest httpRequest) {
        try {
            // 设置回调地址
            request.setNotifyUrl(notifyUrl);

            // 获取客户端IP
            String ip = getClientIp(httpRequest);
            request.setSpbillCreateIp(ip);

            // 创建支付订单
            WeChatPayResponse response = weChatPayService.createPayment(request);
            return R.ok(response);
        } catch (Exception e) {
            log.error("创建微信支付订单失败", e);
            return R.NOT_FOUND("支付订单创建失败: " + e.getMessage());
        }
    }

    /**
     * 微信支付回调通知
     * @param notifyData 通知数据
     * @return 处理结果
     */
    @PostMapping("/wechat/notify")
    public String handleWeChatNotify(@RequestBody String notifyData) throws Exception {
        log.info("收到微信支付回调通知: {}", notifyData);
        return weChatPayService.handleNotify(notifyData);
    }

    /**
     * 获取客户端真实IP
     * @param request HTTP请求
     * @return 客户端IP
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
